package cc.wanforme.fsync.web;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.web.ErrorProperties;
import org.springframework.boot.autoconfigure.web.servlet.error.BasicErrorController;
import org.springframework.boot.web.servlet.error.ErrorAttributes;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import java.util.Collections;
import java.util.Map;

@Controller
@RequestMapping("/error")
public class ErrorController extends BasicErrorController {
    @Value("${server.servlet.context-path:}")
    private String appContext;
    @Value("${front-path}")
    private String frontPath;

    public ErrorController(ErrorAttributes errorAttributes, ErrorProperties errorProperties) {
        super(errorAttributes, errorProperties);
    }

    @Override
    public ModelAndView errorHtml(HttpServletRequest request, HttpServletResponse response) {
        HttpStatus status = getStatus(request);
        Map<String, Object> model = Collections.unmodifiableMap(getErrorAttributes(
                request, getErrorAttributeOptions(request, MediaType.TEXT_HTML)));
        response.setStatus(status.value());

        ModelAndView modelAndView = resolveErrorView(request, response, status, model);
        if (modelAndView != null) {
            return modelAndView;
        } else {
            String originPath = model.get("path").toString();
            // 处理特定url的 404 异常
            if (status == HttpStatus.NOT_FOUND ) {
                boolean re = originPath.startsWith(frontPath);
                if( appContext.equals("") || appContext.equals("/") ) { // "/" 和 "" 都是上面的逻辑
                    re = originPath.startsWith(frontPath);
                } else {
                    re = originPath.startsWith(appContext + frontPath);
                }

                if(re) {
                    return new ModelAndView("/dist/index.html", model);
                }
            }
        }

        return super.errorHtml(request, response);
    }

}